package com.schedule.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schedule.common.R;
import com.schedule.entity.User;
import com.schedule.mapper.UserMapper;
import com.schedule.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param user
     * @param request
     * @return
     */
    @Override
    public R<User> login(User user, HttpServletRequest request) {
        //        1.加密密码
        String password= DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
//        2.根据邮箱查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,user.getEmail());
        User userServiceOne = userService.getOne(queryWrapper);
//        3.判断用户是否存在
        if (userServiceOne==null){
            log.info("当前邮箱未注册");
            return R.error("用户未注册");
        }
//        4.判断密码是否匹配
        if (!userServiceOne.getPassword().equals(password)){
            return R.error("密码错误");
        }
//        5.成功登录，用户id放入session
        request.getSession().setAttribute("userId",userServiceOne.getId());
        R<User> userR=R.success(userServiceOne);
        userR.setMsg("登录成功！");
        return userR;
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    public R<User> register(User user) {

        //1.判断邮箱是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail,user.getEmail());
        int count = userService.count(wrapper);
        if (count!=0){
            return R.error("该邮箱已注册");
        }

        //2.密码加密
        String password=DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        //覆盖原密码
        user.setPassword(password);

        //3.新增用户
        userService.save(user);
        R<User> userR = R.success(user);
        userR.setMsg("注册成功");
        return userR;
    }

    @Override
    public R<User> update(User user) {
        if (user.getId()==null){
            return R.error("userId为空，无法修改信息");
        }
        //密码加密 重置
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(password);

        if(userService.updateById(user)){
            R<User> userR = R.success(userService.getById(user.getId()));
            userR.setMsg("修改成功");
            return userR;
        }

        return R.error("修改失败");
    }
}
